package com.wolf.gulimall.order.listener;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.wolf.gulimall.order.config.AlipayTemplate;
import com.wolf.gulimall.order.service.OrderService;
import com.wolf.gulimall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝回调拦截器
 */
@Slf4j
@RestController
public class OrderPayListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    /**
     * 接收支付宝异步通知消息
     *
     * @param request 请求
     * @return 返回数据
     */
    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException {
        //只要收到支付宝异步通知,订单支付成功消息,发返回success,支付宝结束异步通知
        //1. 需要验签,以防拿到的通知不是支付宝的回调通知,避免伪造数据
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(), alipayTemplate.getSign_type());

        if (signVerified) {
            log.info("签名验证成功...");
            //去修改订单状态
            String result = orderService.handleAliPayResult(payAsyncVo);
            return result;//必须为success,支付宝才会结束异步通知
        } else {
            log.error("签名验证失败...");
            return "error";
        }
    }
}
